package com.hellogood.work.evaluate.server.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.hellogood.work.evaluate.server.db.DBHelper;
import com.hellogood.work.evaluate.shared.exception.DatabaseException;
import com.hellogood.work.evaluate.shared.po.Item;

public class ItemDAO extends DBHelper {

	@Override
	public List<?> initializeObject(ResultSet rs) throws SQLException {
		List<Item> list = new ArrayList<Item>();
		if (rs != null) {
			while (rs.next()) {
				Item item = new Item();
				Object procode = rs.getString("ProCode");
				Object proname = rs.getString("ProName");
				item.setItemCode(procode == null ? "" : procode.toString().trim());
				item.setItemName(proname == null ? "" : proname.toString().trim());				
				list.add(item);
			}
		}
		return list;
	}

	@SuppressWarnings("unchecked")
	public List<Item> getList() {
		String sql = "SELECT * FROM Products ORDER BY ProCode";
		List<?> list = super.query(sql);
		return (List<Item>) list;
	}

	public Item getItem(String proCode) {
		String sql = "SELECT * FROM Products WHERE ProCode = '" + proCode + "'";
		List<?> list = super.query(sql);
		if (list != null && list.size() > 0) {
			return (Item) list.get(0);
		}
		return null;
	}

	public String modify(Item item, boolean isModiy) {
		String sql = "INSERT INTO Products(ProCode,ProName) VALUES('" + item.getItemCode() + "','" + item.getItemName() + "')";
		if (isModiy) {
			sql = "UPDATE Products SET ProducName = '" + item.getItemName() + "' WHERE ProCode = '" + item.getItemCode() + "'";
		}
		try {
			if (super.execute(sql) > 0) {
				return "";
			}
		} catch (DatabaseException e) {
			e.printStackTrace();
			return "执行新建、修改产品信息错误";
		}
		return "执行新建、修改产品信息错误";
	}
}
